package com.atguigu.chapter05.sink;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/17 10:44
 */
public class Flink04_Sink_JDBC {
    public static void main(String[] args) throws Exception {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
    
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .max("vc")
            .addSink(JdbcSink.sink(
                "replace into sensor values(?,?,?)",
                (ps, ws) -> {
                    ps.setString(1, ws.getId());
                    ps.setLong(2, ws.getTs());
                    ps.setInt(3, ws.getVc());
                },
                JdbcExecutionOptions.builder()
                    .withBatchSize(1000)
                    .withBatchIntervalMs(200)
                    .withMaxRetries(5)
                    .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                    .withUrl("jdbc:mysql://hadoop162:3306/test")
                    .withDriverName("com.mysql.jdbc.Driver")
                    .withUsername("root")
                    .withPassword("aaaaaa")
                    .build()
            ));
        
        env.execute();
        
    }
    
}
